package com.tfleo.mealssenger.adapter;

import java.util.HashMap;
import java.util.List;

import com.tfleo.mealssenger.R;
import com.tfleo.mealssenger.object.FriendSelection;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class FriendCheckBoxAdapter extends ArrayAdapter<FriendSelection> {
	private LayoutInflater mInflater;
	private HashMap<Integer, Boolean> mSelected = new HashMap<Integer, Boolean>();
	
	public FriendCheckBoxAdapter(Context context, int resource, int textViewResourceId, 
			List<FriendSelection> objects, LayoutInflater inflater) {
		super(context, resource, textViewResourceId, objects);
		mInflater = inflater;
		
		for(int i = 0; i < objects.size(); i++) {
			mSelected.put(objects.get(i).id, false);
		}
	}
	
	@Override
    public View getView(int position, View convertView, ViewGroup parent) {   
		ViewHolder holder = null;
		TextView name = null;
		CheckBox check = null;
		
		final FriendSelection f = getItem(position);
		
		if(convertView == null) {
			convertView = mInflater.inflate(R.layout.add_share_list_entry, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		}
		
		holder = (ViewHolder) convertView.getTag();
		
		name = holder.getNameView();
		name.setText(f.name);
		
		check = holder.getCheckboxView();
		check.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
		        if(((CheckBox) v).isChecked()) {
		        	mSelected.put(f.id, true);
		        } else {
		        	mSelected.put(f.id, false);
		        }
			}
		});

		return convertView;
	}
	
	public HashMap<Integer, Boolean> getSelected() {
		return mSelected;
	}
	
	private class ViewHolder {
		private View vRow;
		private TextView vName = null;
		private CheckBox vCheckbox = null;

		public ViewHolder(View row) {
			vRow = row;
		}

		public TextView getNameView() {
			if (vName == null) {
				vName = (TextView) vRow.findViewById(R.id.name);
			}
			return vName;
		}

		public CheckBox getCheckboxView() {
			if (vCheckbox == null) {
				vCheckbox = (CheckBox) vRow.findViewById(R.id.check);
			}
			return vCheckbox;
		}
	}
}
